﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for GraphDataService
/// </summary>
public class GraphDataService : IGraphDataService
{
	public GraphDataService()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public List<DataItem> getDataSet(string DateRangeType, string symbol, String StartDate, String EndDate)
    {
        List<DataItem> result = new List<DataItem>();
        String query = toQuery(DateRangeType, symbol, StartDate, EndDate);
        result= queryData(query);
        return result;
    }

    private List<DataItem> queryData(String query)
    {
        List<DataItem> list = new List<DataItem>();
        using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["StockDbConnection"].ToString()))
        {
            cn.Open();
            SqlCommand cmd = new SqlCommand(query, cn);
            SqlDataReader sqldatareader = cmd.ExecuteReader();
            while (sqldatareader.Read())
            {
                DataItem a = new DataItem();
                a.Symbol = sqldatareader.GetString(0);
                a.Price = sqldatareader.GetDouble(1);
                a.Date = sqldatareader.GetDateTime(2);
                list.Add(a);
                System.Diagnostics.Debug.WriteLine("Count " + list.Count);
            }
            cn.Close();
        }
        System.Diagnostics.Debug.WriteLine("Query: " + query);
        return list;
    }

    public string toQuery(string DateRangeType, string symbol, String StartDate, String EndDate)
    {
        IndustryInfoService industryInfoService = new IndustryInfoService();
        String result = "Select * from " ;
        result += DateRangeType+" ";
        result += "Where ";
        result += "symbol = '" + symbol + "' ";
        result += "And ";
        result += "date>='" + formatDate(StartDate) + "' ";
        result += "And ";
        result += "date<='" + formatDate(EndDate) + "' ";
        return result;
    }

    public string formatDate(string date)
    {
        return date;
    }
}